package com.live.task;

import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.live.activity.LiveMemberActivity;
import com.live.activity.R;
import com.live.common.Constant;
import com.live.tools.LiveTools;

public class LiveMemberStats extends AsyncTask<Bundle, Integer, String> {
	private List<Map<String, Object>> memberList;
	private List<Map<String, Object>> homeFirstMemberList = new ArrayList<Map<String, Object>>();
	private List<Map<String, Object>> guestFirstMemberList = new ArrayList<Map<String, Object>>();
	private List<Map<String, Object>> homePlayerMemberList = new ArrayList<Map<String, Object>>();
	private List<Map<String, Object>> guestPlayerMemberList = new ArrayList<Map<String, Object>>();
	private ListView homeFirstMemberView;
	private ListView guestFirstMemberView;
	private ListView homePlayerMemberView;
	private ListView guestPlayerMemberView;

	private String url;

	private Context context = null;

	public SharedPreferences store = null;

	public String matchId = null;
	public String matchOptaId = null;
	public String homeTeam = null;
	public String visitTeam = null;
	public String matchName = null;
	private String matchCategory = null;
	private LinearLayout viewMatch = null;

	public LiveMemberStats(Context context, LinearLayout viewMatch) {
		this.context = context;
		this.viewMatch = viewMatch;
		this.homeFirstMemberView = (ListView) viewMatch.findViewById(R.id.homeFirstMemberList);
		this.guestFirstMemberView = (ListView) viewMatch.findViewById(R.id.guestFirstMemberList);
		this.homePlayerMemberView = (ListView) viewMatch.findViewById(R.id.homePlayerMemberList);
		this.guestPlayerMemberView = (ListView) viewMatch.findViewById(R.id.guestPlayerMemberList);
	}

	// 此方法在主线程执行,当任务执行之前开始调用此方法，可以在这里显示进度对话框
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		Log.i("Comment", "onPreExecute()  " + Thread.currentThread().getId());
	}

	// 此方法在后台线程执行，完成任务的主要工作，通常需要较长的时间。
	// 在执行过程中可以调用publicProgress(Progress...)来更新任务的进度。

	@Override
	protected String doInBackground(Bundle... params) {
		Log.i("Comment", "doInBackground... " + Thread.currentThread().getId());

		matchId = params[0].getString("matchId");
		matchOptaId = params[0].getString("matchOptaId");
		homeTeam = params[0].getString("homeTeam");
		visitTeam = params[0].getString("visitTeam");
		matchName = params[0].getString("matchName");
		matchCategory = params[0].getString("matchCategory");

		// 国际足球使用optaId
		if ("2".equals(matchCategory) && !"".equals(matchOptaId)) {
			matchId = matchOptaId;
		}

		url = Constant.SITE_URL + "live_member_stats.php?locale=" + LiveTools.getLocaleLanguage() + "&matchId="
				+ matchId + "&matchCategory=" + matchCategory;
		memberList = getMember(url);

		for (int i = 0; i < memberList.size(); i++) {
			Map<String, Object> member = memberList.get(i);
			if ("1".equals((String) member.get("team"))) {
				if ("Y".equals((String) member.get("first"))) {
					homeFirstMemberList.add(member);
				} else {
					homePlayerMemberList.add(member);
				}
			} else {
				if ("Y".equals((String) member.get("first"))) {
					guestFirstMemberList.add(member);
				} else {
					guestPlayerMemberList.add(member);
				}
			}
		}
		publishProgress();
		return null;
	}

	// 此方法在主线程执行，用于显示任务执行的进度
	@Override
	protected void onProgressUpdate(Integer... values) {
		super.onProgressUpdate(values);
		Log.i("PageTask", "onProgressUpdate()  " + Thread.currentThread().getId());

		SimpleAdapter adapter;

		adapter = new SimpleAdapter(context, homeFirstMemberList, R.layout.mumber_home_list, new String[] { "name",
				"no" }, new int[] { R.id.name, R.id.no });
		homeFirstMemberView.setAdapter(adapter);
		homeFirstMemberView.setOnItemClickListener(new OnItemClickListener() {

			// 从当前画面到球员明细画面跳转，并传值。
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

				Map<String, Object> member = homeFirstMemberList.get(arg2);

				Intent intent = new Intent();

				intent.setClass(context, LiveMemberActivity.class);

				// 实例化 Bundle，设置需要传递的参数
				Bundle bundle = new Bundle();
				bundle.putString("matchId", matchId);
				bundle.putString("id", member.get("id").toString());
				bundle.putString("name", member.get("name").toString());
				bundle.putString("team", "1:" + homeTeam);
				bundle.putString("macthName", matchName);
				bundle.putString("matchCategory", matchCategory);

				intent.putExtras(bundle);

				context.startActivity(intent);
			}
		});

		adapter = new SimpleAdapter(context, guestFirstMemberList, R.layout.mumber_guest_list, new String[] { "name",
				"no" }, new int[] { R.id.name, R.id.no });
		guestFirstMemberView.setAdapter(adapter);

		guestFirstMemberView.setOnItemClickListener(new OnItemClickListener() {

			// 从当前画面到球员明细画面跳转，并传值。
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

				Map<String, Object> member = guestFirstMemberList.get(arg2);

				Intent intent = new Intent();

				intent.setClass(context, LiveMemberActivity.class);

				// 实例化 Bundle，设置需要传递的参数
				Bundle bundle = new Bundle();
				bundle.putString("matchId", matchId);
				bundle.putString("id", member.get("id").toString());
				bundle.putString("name", member.get("name").toString());
				bundle.putString("team", "2:" + visitTeam);
				bundle.putString("macthName", matchName);
				bundle.putString("matchCategory", matchCategory);

				intent.putExtras(bundle);

				context.startActivity(intent);
			}
		});

		adapter = new SimpleAdapter(context, homePlayerMemberList, R.layout.mumber_home_list, new String[] { "name",
				"no" }, new int[] { R.id.name, R.id.no });
		homePlayerMemberView.setAdapter(adapter);
		homePlayerMemberView.setOnItemClickListener(new OnItemClickListener() {

			// 从当前画面到球员明细画面跳转，并传值。
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

				Map<String, Object> member = homePlayerMemberList.get(arg2);

				Intent intent = new Intent();

				intent.setClass(context, LiveMemberActivity.class);

				// 实例化 Bundle，设置需要传递的参数
				Bundle bundle = new Bundle();
				bundle.putString("matchId", matchId);
				bundle.putString("id", member.get("id").toString());
				bundle.putString("name", member.get("name").toString());
				bundle.putString("team", "1:" + homeTeam);
				bundle.putString("macthName", matchName);
				bundle.putString("matchCategory", matchCategory);

				intent.putExtras(bundle);

				context.startActivity(intent);
			}
		});

		adapter = new SimpleAdapter(context, guestPlayerMemberList, R.layout.mumber_guest_list, new String[] { "name",
				"no" }, new int[] { R.id.name, R.id.no });
		guestPlayerMemberView.setAdapter(adapter);
		guestPlayerMemberView.setOnItemClickListener(new OnItemClickListener() {

			// 从当前画面到球员明细画面跳转，并传值。
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

				Map<String, Object> member = guestPlayerMemberList.get(arg2);

				Intent intent = new Intent();

				intent.setClass(context, LiveMemberActivity.class);

				// 实例化 Bundle，设置需要传递的参数
				Bundle bundle = new Bundle();
				bundle.putString("matchId", matchId);
				bundle.putString("id", member.get("id").toString());
				bundle.putString("name", member.get("name").toString());
				bundle.putString("team", "2:" + visitTeam);
				bundle.putString("macthName", matchName);
				bundle.putString("matchCategory", matchCategory);

				intent.putExtras(bundle);

				context.startActivity(intent);
			}
		});

	}

	// 此方法在主线程执行，任务执行的结果作为此方法的参数返回。
	@Override
	protected void onPostExecute(String result) {
		// tv.setText(result);
		Log.i("PageTask", "onPostExecute()  " + Thread.currentThread().getId());

		LinearLayout loadData = (LinearLayout) viewMatch.findViewById(R.id.loadData);
		viewMatch.removeView(loadData);
	}

	private List<Map<String, Object>> getMember(String url) {
		List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
		HttpClient client = new DefaultHttpClient();
		// 提拱默认的HttpClient实现
		HttpPost request;
		try {
			request = new HttpPost(new URI(url));
			HttpResponse response = client.execute(request);
			// 判断请求是否成功
			if (response.getStatusLine().getStatusCode() == 200) { // 200表示请求成功
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					String out = EntityUtils.toString(entity);
					try {
						String result = new JSONObject(out).getString("result");
						if (Constant.Y.equals(result)) {
							JSONArray member = new JSONObject(out).getJSONArray("results");
							for (int i = 0; i < member.length(); i++) {
								Map<String, Object> map = new HashMap<String, Object>();
								map.put("id", member.getJSONObject(i).get("id"));
								map.put("no", member.getJSONObject(i).get("no"));
								map.put("name", member.getJSONObject(i).get("name"));
								map.put("first", member.getJSONObject(i).get("first"));
								map.put("team", member.getJSONObject(i).get("team"));
								data.add(map);
							}
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return data;
	}

}